import { defineStore } from "pinia";
import VtOrderAPI from "@/api/vt/vt-order.js";
import SoundService from "@/utils/notification";
import { hasAuth } from "@/plugins/permission";

export const useVtOrderStore = defineStore("vtOrder", {
  state: () => ({
    // 报价单列表数据
    orderList: [],
    total: 0,
    loading: false,
    loaded: false,

    // 定时器
    refreshTimer: null,
    currentQueryParams: { pageNum: 1, pageSize: 5 },

    // 通知设置
    notificationEnabled: true,
    soundEnabled: true,

    // 上次数据状态（用于比较变化）
    lastDataState: {
      total: 0,
      statusCounts: {},
      lastUpdateTime: null,
    },
  }),

  getters: {
    /**
     * 获取待处理报价单数量
     */
    getPendingCount: (state) => {
      return state.orderList.filter((order) => order.status === 0).length;
    },

    /**
     * 获取各状态报价单数量统计
     */
    getStatusCounts: (state) => {
      const counts = { 0: 0, 1: 0, 2: 0, 3: 0 };
      state.orderList.forEach((order) => {
        if (Object.prototype.hasOwnProperty.call(counts, order.status)) {
          counts[order.status]++;
        }
      });
      return counts;
    },

    /**
     * 检查是否有权限接收通知
     */
    canReceiveNotifications: (state) => {
      return state.notificationEnabled && SoundService.notificationEnabled;
    },
  },

  actions: {
    /**
     * 加载通知设置
     */
    loadNotificationSettings() {
      // 加载声音设置
      const soundSetting = localStorage.getItem("vt_order_sound_enabled") || "1";
      if (soundSetting !== null) {
        this.soundEnabled = soundSetting === "1";
      }

      // 加载通知设置
      const notificationSetting = localStorage.getItem("vt_order_notification_enabled") || "1";
      if (notificationSetting !== null) {
        this.notificationEnabled = notificationSetting === "1";
      }

      // 加载上次数据状态
      const lastState = localStorage.getItem("vt_order_last_state");
      if (lastState) {
        try {
          this.lastDataState = JSON.parse(lastState);
        } catch (error) {
          console.error("解析上次报价单状态失败:", error);
        }
      }
    },

    /**
     * 保存通知设置
     */
    saveNotificationSettings() {
      localStorage.setItem("vt_order_sound_enabled", this.soundEnabled ? "1" : "0");
      localStorage.setItem("vt_order_notification_enabled", this.notificationEnabled ? "1" : "0");
    },

    /**
     * 保存当前数据状态
     */
    saveCurrentDataState() {
      const currentState = {
        total: this.total,
        statusCounts: this.getStatusCounts,
        lastUpdateTime: new Date().toISOString(),
      };

      localStorage.setItem("vt_order_last_state", JSON.stringify(currentState));
      this.lastDataState = currentState;
    },

    /**
     * 切换声音通知
     */
    toggleSound() {
      this.soundEnabled = !this.soundEnabled;
      this.saveNotificationSettings();
    },

    /**
     * 切换桌面通知
     */
    toggleNotification() {
      this.notificationEnabled = !this.notificationEnabled;
      this.saveNotificationSettings();
    },

    /**
     * 获取报价单列表数据
     */
    async fetchOrderList(queryParams = { pageNum: 1, pageSize: 3 }) {
      if (this.loading) return;

      this.loading = true;
      try {
        const data = await VtOrderAPI.getPage(queryParams);
        const newOrderList = data.list || [];
        const newTotal = data.total || 0;

        // 检查数据变化并发送通知
        this.checkDataChangesAndNotify(newOrderList);

        // 更新数据
        this.orderList = newOrderList;
        this.total = newTotal;
        this.loaded = true;

        // 保存当前状态
        this.saveCurrentDataState();

        return data;
      } catch (error) {
        console.error("获取报价单列表失败:", error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 检查数据变化并发送通知
     */
    checkDataChangesAndNotify(newOrderList) {
      if (!this.loaded || !this.canReceiveNotifications) {
        return;
      }

      const newTotal = this.total;
      const newStatusCounts = this.calculateStatusCounts(newOrderList);

      // 检查总数变化
      if (newTotal > this.lastDataState.total) {
        const newOrdersCount = newTotal - this.lastDataState.total;
        this.showNewOrderNotification(newOrdersCount);
      }

      // 检查待处理报价单数量变化
      const newPendingCount = newStatusCounts[0] || 0;
      const oldPendingCount = this.lastDataState.statusCounts[0] || 0;

      if (newPendingCount > oldPendingCount) {
        const newPendingOrders = newPendingCount - oldPendingCount;
        this.showPendingOrderNotification(newPendingOrders);
      }

      // 检查状态变化
      this.checkStatusChanges(newStatusCounts);
    },

    /**
     * 计算状态统计
     */
    calculateStatusCounts(orderList) {
      const counts = { 0: 0, 1: 0, 2: 0, 3: 0 };
      orderList.forEach((order) => {
        if (Object.prototype.hasOwnProperty.call(counts, order.status)) {
          counts[order.status]++;
        }
      });
      return counts;
    },

    /**
     * 检查状态变化
     */
    checkStatusChanges(newStatusCounts) {
      const statusLabels = {
        0: "待处理",
        1: "已处理",
        2: "已确定",
        3: "处理中",
      };

      Object.keys(newStatusCounts).forEach((status) => {
        const newCount = newStatusCounts[status];
        const oldCount = this.lastDataState.statusCounts[status] || 0;
        if (newCount > oldCount && status !== "0") {
          // 待处理报价单单独处理
          const changeCount = newCount - oldCount;
          const statusLabel = statusLabels[status];
          this.showStatusChangeNotification(statusLabel, changeCount);
        }
      });
    },

    /**
     * 显示新报价单通知
     */
    async showNewOrderNotification(count) {
      if (!this.soundEnabled && !this.notificationEnabled) return;
      if (!hasAuth("vt:vt-order-form:handle")) {
        console.log("业务员不接收新报价单通知！");
        return;
      }

      const title = "新报价单提醒";
      const message = `有 ${count} 个新报价单需要处理`;

      await SoundService.showNewMessageNotification(title, message, () => {
        // 点击通知时的处理
        window.focus();
      });
    },

    /**
     * 显示待处理报价单通知
     */
    async showPendingOrderNotification(count) {
      if (!this.soundEnabled && !this.notificationEnabled) return;

      const title = "待处理报价单";
      const message = `新增 ${count} 个待处理报价单`;

      await SoundService.showNewMessageNotification(title, message, () => {
        window.focus();
      });
    },

    /**
     * 显示状态变化通知
     */
    async showStatusChangeNotification(statusLabel, count) {
      if (!this.soundEnabled && !this.notificationEnabled) return;

      const title = "报价单状态更新";
      const message = `有 ${count} 个报价单状态变更为${statusLabel}`;

      await SoundService.showNewMessageNotification(title, message, () => {
        window.focus();
      });
    },

    /**
     * 启动定时刷新
     */
    startAutoRefresh(queryParams = { pageNum: 1, pageSize: 3 }) {
      // 清除现有定时器
      this.stopAutoRefresh();

      // 保存查询参数
      this.currentQueryParams = queryParams;

      // 设置30秒定时刷新
      this.refreshTimer = setInterval(() => {
        this.fetchOrderList(this.currentQueryParams);
      }, 30000);

      console.log("报价单数据定时刷新已启动 (30秒间隔)");
    },

    /**
     * 停止定时刷新
     */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
        console.log("报价单数据定时刷新已停止");
      }
    },

    /**
     * 初始化报价单数据管理
     */
    async initialize() {
      // 加载通知设置
      this.loadNotificationSettings();

      // 初始加载数据
      await this.fetchOrderList();

      // 启动定时刷新
      this.startAutoRefresh();
    },

    /**
     * 更新本地报价单状态（避免自己修改的数据发送通知）
     */
    updateLocalOrderStatus(orderId, newStatus) {
      const order = this.orderList.find((item) => item.id === orderId);
      if (order) {
        order.status = newStatus;
        // 更新本地状态缓存，避免下次刷新时误判为新变化
        this.saveCurrentDataState();
      }
    },

    /**
     * 清理资源
     */
    cleanup() {
      this.stopAutoRefresh();
    },
  },
});

// 导出store hook
export const useVtOrderStoreHook = () => {
  return useVtOrderStore();
};
